package shop.user.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import shop.common.core.Result;
import shop.common.entity.User;
import shop.user.service.UserService;

@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping("/test")
    public Result test() {
        return Result.ok().data("Hello World");
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        boolean save = userService.save(user);
        return save ? Result.ok() : Result.fail();
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user) throws Exception {
        String token = userService.login(user.getUsername(), user.getPassword());
        return StringUtils.hasLength(token) ? Result.ok().data(token) : Result.fail();
    }

    @DeleteMapping("/remove/{id}")
    public Result remove(@PathVariable("id") String id) {
        boolean flag = userService.removeById(id);
        return flag ? Result.ok() : Result.fail();
    }

    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        boolean bool = userService.updateById(user);
        return bool ? Result.ok() : Result.fail();
    }


    @GetMapping("/details/{id}")
    public Result details(@PathVariable String id) {
        User user = userService.getById(id);
        return Result.ok().data(user);
    }

    @GetMapping("/details")
    public Result get(@RequestParam String username) {
        User one = userService.getByUsername(username);
        return Result.ok().data(one);
    }
    @PostMapping("/list")
    public Result list(@RequestBody User user, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        Page<User> page = userService.list(user, pageNum, pageSize);
        return Result.ok().data(page);
    }


    @GetMapping("/exist")
    public Result exist(@RequestParam String username) {
        return Result.ok().data(userService.exist(username));
    }
}
